/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.itip.tivoli;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.sinodata.bsm.common.vo.Event;
import com.sinodata.bsm.common.vo.EventType;
import com.sinodata.bsm.common.vo.Res;
import com.sinodata.bsm.itip.cache.CacheFactory;
import com.sinodata.bsm.itip.cache.EventTypeCache;
import com.sinodata.bsm.itip.cache.ResCache;
import com.sinodata.bsm.itip.cache.ResTypeCache;
import com.sinodata.bsm.itip.event.TivoliEvent;
import com.sinodata.bsm.itip.message.Messenger;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author wangyazhou
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2013-2-27 下午3:47:06          wangyazhou        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class OmnibusToEventUtil {
    private static final Logger logger = Logger.getLogger("event");
    private static final Logger flogger = Logger.getLogger("event_f");

    private static OmnibusToEventUtil instance = null;

    private ResCache resCache = (ResCache) CacheFactory.getCache(ResCache.class);

    private EventTypeCache eventTypeCache = (EventTypeCache) CacheFactory.getCache(EventTypeCache.class);

    private ResTypeCache resTypeCache = (ResTypeCache) CacheFactory.getCache(ResTypeCache.class);

    //    private static final SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private final SimpleDateFormat sdf1 = new SimpleDateFormat("MM/dd/yy HH:mm:ss.SSS");

    private OmnibusToEventUtil() {

    }

    public static synchronized OmnibusToEventUtil getInstance() {
        if (instance == null) {
            instance = new OmnibusToEventUtil();
        }
        return instance;
    }

    /**
     * 发送事件 
     * @param json
     * @return
     */
    public void send(List<TivoliEvent> events) {
        logger.info("[TIP]\tReceive Event. Size = " + events.size());
        for (int i = 0; i < events.size(); i++) {
            TivoliEvent tivoli = events.get(i);
            Event event = new Event();
            try {
                Res res = resCache.getResIdByIId(tivoli.getNode());

                if (res == null) {
                    flogger.info("[RUDE]\t" + tivoli.toString());
                    flogger.info("[TIP]\tNot Find Res Whose Inid Is :" + tivoli.getNode());
                    continue;
                }
                event.setResId(res.getId()); //资源id
                Date createDate = null;

                try {
                    createDate = sdf1.parse(tivoli.getItmTime());
                } catch (Exception e) {
                    try {
                        createDate = sdf1.parse(sdf1.format(Long.parseLong(tivoli.getItmTime())));
                    } catch (Exception e2) {
                    }
                }

                event.setOccurTime(createDate == null ? new Date() : createDate);//产生时间
                //                Long eventTypesId = eventTypeCache.getByCode(tivoli.getTypeCode()).getId();
                //                if (eventTypesId == null) {
                //                    continue;
                //                }
                //                event.setEventTypeId(eventTypesId);//类别id 
                //                event.setEventTypeId(210100000000001L);//类别id   
                event.setEventTypeId(toBsmEventType(res.getResTypeId()));//类别id   
                event.setMsg(tivoli.getSummary());//事件详情      
                int level = toBsmLevel(tivoli.getSeverity());
                if (1 == level) {
                    event.setLevel(1);//级别   
                    event.setStatus(2); //新事件         
                    event.setCatalog(2); //故障恢复类事件
                } else {
                    event.setLevel(level);//级别   
                    event.setStatus(0); //新事件         
                    event.setCatalog(1); //故障类事件
                }

                event.setObjectId(tivoli.getSerial()); //

                logger.info("[EVENT]\t" + event.toString());
                //放入MQ的事件队列
                Messenger.getInstance().sendEvent(event);
            } catch (Exception e) {
                flogger.info("[ERROR]\t" + event.toString() + "\n", e);
            }
        }
    }

    /**
     * 获取资源的事件类别
     * @param res
     * @return
     */
    private Long toBsmEventType(Long resTypeId) {
        List<EventType> types = eventTypeCache.findByResTypeId(resTypeId);
        if (types == null || types.size() < 1) {
            Long pTypeId = resTypeCache.get(resTypeId).getParentId();
            if (pTypeId != null && pTypeId.longValue() > 1L) {
                return toBsmEventType(pTypeId);
            }
        } else {
            return types.get(0).getId();
        }
        return 1L;
    }

    private Integer toBsmLevel(String severity) {
        String retVal = "3";
        switch (Integer.parseInt(severity)) {
            case 0:
                retVal = "1";
                break;
            case 1:
                retVal = "2";
                break;
            case 2:
                retVal = "3";
                break;
            case 3:
                retVal = "3";
                break;
            case 4:
                retVal = "4";
                break;
            case 5:
                retVal = "5";
                break;
        }
        return Integer.parseInt(retVal);
    }

    public static void main(String[] args) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long time = new Long(1385536934);
        String d = format.format(time);
        Date date = format.parse(d);
        System.out.println("Format To String(Date):" + d);
        System.out.println("Format To Date:" + date);
    }
}
